package com.huixuebao.pay.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.huixuebao.common.bean.ApiResult;
import com.huixuebao.pay.entity.PayOrderEntity;
import com.huixuebao.pay.mapper.PayOrderMapper;
import com.huixuebao.pay.service.PayOrderService;
import com.huixuebao.pay.service.rpc.InsureOrderService;
import com.huixuebao.payinterface.dto.PayDTO;
import com.huixuebao.payinterface.enumeration.PayStatusEnum;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

@Slf4j
@RestController()
@RequestMapping("/wxPay")
public class WxPayController {

    private final WxPayService wxPayService;

    @Autowired
    PayOrderMapper payOrderMapper;

    @Autowired
    private InsureOrderService insureOrderService;

    @Autowired
    private PayOrderService payService;

    @Autowired
    public WxPayController(WxPayService wxPayService) {
        this.wxPayService = wxPayService;
    }

    /**
     * 获取支付订单
     * @param payDTO
     * @return
     */
    @PostMapping("/createOrder")
    public ApiResult createOrder(@RequestBody PayDTO payDTO) {
        ApiResult apiResult = new ApiResult();
        try{
            String payOrderId = IdUtil.simpleUUID();
            WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
            orderRequest.setDeviceInfo("web");
            orderRequest.setTradeType(WxPayConstants.TradeType.JSAPI);
            orderRequest.setBody(payDTO.getCourseName());
            orderRequest.setOutTradeNo(payOrderId);
            orderRequest.setTotalFee(Integer.valueOf(payDTO.getPrice())); //商品价格，单位分
            orderRequest.setSpbillCreateIp("127.0.0.1");
            orderRequest.setProductId(payOrderId);
            String openId = payDTO.getOpenId();
            orderRequest.setOpenid(openId);
            WxPayMpOrderResult wxPayMpOrderResult = wxPayService.createOrder(orderRequest);
            PayOrderEntity payOrderEntity = new PayOrderEntity();
            payOrderEntity.setPhone(payDTO.getPhone());
            payOrderEntity.setId(payOrderId);
            payOrderEntity.setPolicyId(payDTO.getPolicyId());
            payOrderEntity.setStatus(PayStatusEnum.PROCESSING);
            payOrderEntity.setCreateTime(new DateTime());
            payOrderEntity.setPayPrice(new BigDecimal(payDTO.getPrice()));

            payOrderMapper.insert(payOrderEntity);
            apiResult.setSuccess(true);
            apiResult.setData(wxPayMpOrderResult);
        }catch(Exception ex){
            log.error("createOrder:" + ex.getMessage());
            apiResult.setSuccess(false);
            apiResult.setMessage(ex.getMessage());
        }
        return apiResult;
    }
    /**
     * 如果理赔金额大于课程价格更新订单状态
     * @param payDTO
     * @return
     */
    @PostMapping("/updateOrder")
    public ApiResult updateOrder(@RequestBody PayDTO payDTO) {
        ApiResult apiResult = new ApiResult();
        try{
            String orderId = IdUtil.simpleUUID();
            PayOrderEntity payOrderEntity = new PayOrderEntity();
            payOrderEntity.setId(orderId);

            payOrderEntity.setPolicyId(payDTO.getPolicyId());
            payOrderEntity.setStatus(PayStatusEnum.PROCESSING);
            payOrderMapper.insert(payOrderEntity);
            apiResult.setSuccess(true);
        }catch(Exception ex){
            log.error("createOrder:" + ex.getMessage());
            apiResult.setSuccess(false);
            apiResult.setMessage(ex.getMessage());
        }
        return apiResult;
    }
    /**
     * 微信支付回调
     * @param xmlData
     * @return
     */
    @RequestMapping("/notify")
    public String notify(@RequestBody String xmlData){
        try {
            log.info("进入到回调接口!!!"+ xmlData);
            if (StrUtil.isNotEmpty(xmlData)) {
                WxPayOrderNotifyResult result = wxPayService.parseOrderNotifyResult(xmlData);
                log.info("进入到回调接口");
                PayOrderEntity payOrderEntity;
                if (StrUtil.isNotEmpty(result.getOutTradeNo())) {
                    payOrderEntity = payOrderMapper.selectById(result.getOutTradeNo());
                    if ("SUCCESS".equals(result.getReturnCode()) && "SUCCESS".equals(result.getResultCode())){
                        log.info("支付成功");
                        payOrderEntity.setStatus(PayStatusEnum.SUCCESS);
                        payOrderEntity.setPayTime(new DateTime());
                        payOrderEntity.setUpdateTime(new DateTime());
                        insureOrderService.updateStateAfterPay(payOrderEntity.getPolicyId(),"3");
                    } else {
                        log.info("支付失败");
                        payOrderEntity.setStatus(PayStatusEnum.FAILURE);
                    }
                    payOrderEntity.setChannelOrderId(result.getTransactionId());
                    payOrderMapper.updateById(payOrderEntity);
                }
            }
        } catch (WxPayException e) {
            log.error("parseScanPayNotifyResult:" + e.toString(), e);
        }
        return WxPayNotifyResponse.success("成功");
    }
    /**
     * 获取openId
     * @param code
     * @return
     */
    @GetMapping("/getUserCode")
    public ApiResult getUserCode(@RequestParam String code) {

        ApiResult apiResult = new ApiResult();
        try {
            WxMpDefaultConfigImpl configStorage = new WxMpDefaultConfigImpl();
            configStorage.setAppId("wxce853ff38e71b054");
            configStorage.setSecret("6fc7f62eb738dad16e2797798aa44d51");

            WxMpService wxMpService = new WxMpServiceImpl();
            wxMpService.setWxMpConfigStorage(configStorage);
            WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.getOAuth2Service().getAccessToken(code);
            apiResult.setData(wxMpOAuth2AccessToken.getOpenId());
            apiResult.setSuccess(true);
        }catch (Exception e){
            log.error("获取openId失败{}:" + e.getMessage());
            apiResult.setSuccess(false);
        }
        return apiResult;
    }
    /**
     * 根据保单号查询支付订单详情
     * @param policyId
     * @return
     */
    @GetMapping("/getSettleDetails")
    public ApiResult getSettleDetails(@RequestParam String policyId){return payService.settleDetails(policyId);}
}
